from PIL import Image, ImageDraw
import base64
import random
import os

# -------------------
# 配置
# -------------------
JSON_FILE = "live.json"       # 输入的JSON
OUTPUT_IMAGE = JSON_FILE.replace('.json', '.png')  # 输出图片与JSON同名
TAIL_MARKER = b"JSONTAIL**"   # 尾部标记，方便提取

# -------------------
# 生成极简表情包图片
# -------------------
def generate_emoji_image(path, width=200, height=200):
    """
    生成一个极简风格的表情包图片
    """
    # 创建白色背景图片
    img = Image.new("RGB", (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    
    # 绘制圆形脸
    face_radius = min(width, height) // 3
    face_center = (width // 2, height // 2)
    draw.ellipse([(face_center[0]-face_radius, face_center[1]-face_radius),
                 (face_center[0]+face_radius, face_center[1]+face_radius)],
                 fill=(255, 255, 0), outline=(0, 0, 0))
    
    # 绘制眼睛
    eye_radius = face_radius // 5
    draw.ellipse([(face_center[0]-face_radius//2-eye_radius, face_center[1]-face_radius//3-eye_radius),
                 (face_center[0]-face_radius//2+eye_radius, face_center[1]-face_radius//3+eye_radius)],
                 fill=(0, 0, 0))
    draw.ellipse([(face_center[0]+face_radius//2-eye_radius, face_center[1]-face_radius//3-eye_radius),
                 (face_center[0]+face_radius//2+eye_radius, face_center[1]-face_radius//3+eye_radius)],
                 fill=(0, 0, 0))
    
    # 绘制嘴巴
    mouth_width = face_radius // 2
    draw.arc([(face_center[0]-mouth_width, face_center[1]-mouth_width//2),
             (face_center[0]+mouth_width, face_center[1]+mouth_width//2)],
             start=0, end=180, fill=(0, 0, 0), width=3)
    
    img.save(path, format="PNG", optimize=True)
    print(f"✅ 已生成表情包图片: {path} (大小约 {os.path.getsize(path)/1024:.1f} KB)")

# -------------------
# 读取JSON并清理
# -------------------
def load_json_clean(json_file):
    with open(json_file, "r", encoding="utf-8") as f:
        json_text = f.read()
    # 去掉制表符
    return json_text

# -------------------
# 尾插JSON → PNG
# -------------------
def append_json_to_image(img_file, json_text, output_file):
    with open(img_file, "rb") as f:
        img_bytes = f.read()

    json_base64 = base64.b64encode(json_text.encode("utf-8"))
    final_bytes = img_bytes + TAIL_MARKER + json_base64

    with open(output_file, "wb") as f:
        f.write(final_bytes)

    print(f"✅ 已生成带JSON的图片: {output_file} (大小约 {os.path.getsize(output_file)/1024:.1f} KB)")

# -------------------
# 主流程
# -------------------
if __name__ == "__main__":
    temp_image = "temp.png"

    # 1. 生成表情包图片
    generate_emoji_image(temp_image, width=220, height=220)

    # 2. 读取 & 清理JSON
    json_text = load_json_clean(JSON_FILE)

    # 3. 尾插JSON
    append_json_to_image(temp_image, json_text, OUTPUT_IMAGE)

    # 清理中间文件
    os.remove(temp_image)
